#include <iostream>
#include <string>
#include <gmp.h>
#include <gmpxx.h>
#include <string>
#include <fstream>
#include <sstream>
#include <cstdlib>

#define BITS_PER_DIGIT 3.32192809488736234787;

void monte_carlo(unsigned int points, unsigned int iterations) {
	mpf_class *pi0, *pi1;
	mpf_class eq_cmp("1E-10000000");
	// mpf_class eq_cmp("1E-3");
	
	int cmpr;
	int iteration = 0;

	pi0 = new mpf_class(0);
	pi1 = new mpf_class(0);

	mpf_class denominator(0);
	mpf_class nominator(0);

	do {		

		std::cout << "Starting to calculate iteration #" << ++iteration << std::endl;

		denominator += points;
		unsigned int addToNominator = 0;
		for (unsigned int i = 0; i < points; ++i)
		{
			double x = rand() / (double)RAND_MAX;
			double y = rand() / (double)RAND_MAX;
			if (x * x + y * y <= 1) addToNominator++;
		}
		nominator += addToNominator;

		*pi1 = 4 * (nominator/denominator);

		cmpr = cmp(abs(*pi1 - *pi0), eq_cmp);

		std::swap(pi0, pi1);

		std::stringstream ss;
		ss << "MCST_Iteracao_" << iteration << ".txt";
		std::fstream file;
		file.open(ss.str().c_str(), std::fstream::out);
		file.setf(std::ios::fixed, std::ios::floatfield);
		file.precision(10000000);
		file << *pi0 << std::endl;

	} while (cmpr >= 0 && iteration < iterations);

	delete pi0;
	delete pi1;
}

int main(int argc, char *argv[]) {
	mpf_set_default_prec((long int)(3.32192809488736234787 * 10000100.0));

	std::cout << "Bem vindo ao programa que calcula o PI!\n";
	std::cout << "Esse metodo nao funciona corretamente!\n";
	std::cout << "3-5 casas do pi serao calculadas!\n";
	std::cout << "Arquivos de prefixo \"MCST_\" serao criados\n";

	std::cout.setf(std::ios::fixed, std::ios::floatfield);
	std::cout.precision(10000000);

	monte_carlo(100000000, 50);
	return 0;
}